//
//  StickyHeadersViewController.swift
//  CustomizeCollectionView
//
//  Created by GZOffice_hao on 2019/4/28.
//  Copyright © 2019 VT. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let headerReuseIdentifier = "StikcyHeaderCell"

class StickyHeadersViewController: UICollectionViewController {
    
    let images = allImages()

    override func viewDidLoad() {
        super.viewDidLoad()
//        if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
//            layout.sectionHeadersPinToVisibleBounds = true
//        }
    }
    
    static func allImages() -> [UIImage] {
        return (1...13).map { i -> UIImage in
            return UIImage(named: String(format:"%02d", i))!
        }
    }
}

extension StickyHeadersViewController {
    
    // MARK: UICollectionViewDataSource
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return images.count
    }
    
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! StickyImageCell
        
        // Configure the cell
        cell.image = images[indexPath.section]
        
        return cell
    }
    
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        guard kind == UICollectionView.elementKindSectionHeader, let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerReuseIdentifier, for: indexPath) as? StikcyHeader else {
            return super.collectionView(collectionView, viewForSupplementaryElementOfKind: kind, at: indexPath)
        }
        
        
        return header
    }
}
